package com.zf.yichat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.google.common.collect.Maps;
import com.zf.yichat.mapper.UserBankXsMapper;
import com.zf.yichat.mapper.UserMapper;
import com.zf.yichat.model.User;
import com.zf.yichat.model.UserBankXs;
import com.zf.yichat.model.UserTrade;
import com.zf.yichat.service.BalanceService;
import com.zf.yichat.service.PushService;
import com.zf.yichat.service.XsPayService;
import com.zf.yichat.service.config.ConfigPay;
import com.zf.yichat.utils.HttpProtocolHandler;
import com.zf.yichat.utils.XSpay.TransForm.*;
import com.zf.yichat.utils.XSpay.XSpayService;
import com.zf.yichat.utils.XSpay.util.XSpayException;
import com.zf.yichat.utils.XmlUtils;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.DateUtils;
import com.zf.yichat.utils.common.GeneralUtils;
import com.zf.yichat.utils.common.NumberUtils;
import com.zf.yichat.utils.common.Sign;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.BalanceType;
import com.zf.yichat.vo.PayType;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

@Service
public class XsPayServiceImpl implements XsPayService {
    private String prepay = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    private static Logger logger = LoggerFactory.getLogger(XsPayServiceImpl.class);

    @Autowired
    private BalanceService balanceService;
    @Autowired
    private PushService pushService;
    @Resource
    private UserBankXsMapper userBankXsMapper;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private ConfigPay configPay;

    @Override
    public Map<String, String> weixinPrePay(Long userId, Integer tradeType, BigDecimal money) {
        //暂时订单号使用
        String out_trade_no = DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS") + userId;
        //生成交易记录
        balanceService.createTradeRecord(userId, out_trade_no, money, PayType.WEIXIN, tradeType);

        String body = "用户" + userId + "微信充值";

        String ip = "127.0.0.1";
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        String response = HttpProtocolHandler.getInstance().doPostXml(prepay, XmlUtils.mapToXML(prePayParams(out_trade_no, money, GeneralUtils.getRandomStringByLength(16), configPay.getWeixin().getNotifyUrl(), ip, body)), "utf-8");

        String prePayId = getPrepayId(response);
        // pay params
        return StringUtils.isNoneBlank(prePayId) ? payParamsAPP(GeneralUtils.getRandomStringByLength(16), prePayId, out_trade_no) : null;
    }


    /**
     * 支付的参数列表-APP
     */
    private Map<String, String> payParamsAPP(String nonce_str, String prepayId, String outTradeNo) {
        Map<String, String> result = Maps.newHashMap(); // 调起支付 参数
        result.put("appid", configPay.getWeixin().getAppId()); // 微信开放平台审核通过的应用APPID
        result.put("partnerid", configPay.getWeixin().getMchId()); // 微信支付分配的商户号
        result.put("package", "Sign=WXPay"); // 扩展字段，暂填写固定值Sign=WXPay
        result.put("noncestr", nonce_str); //随机字符串，不长于32位。推荐随机数生成算法
        long time = System.currentTimeMillis();
        //mysq 时间戳只有10位 要做处理
        String dateline = time + "";
        dateline = dateline.substring(0, 10);
        result.put("timestamp", dateline); // 时间戳，请见接口规则-参数规定
        result.put("prepayid", prepayId);// 微信返回的支付交易会话ID
        result.put("sign", Sign.createSign(result, configPay.getWeixin().getAppKey()));// 签名
        return result;
    }


    private Map<String, String> prePayParams(String outTradeNo, BigDecimal totalFee, String nonce_str, String notifyUrl, String ip, String body) {
        Map<String, String> map = Maps.newHashMap();
        map.put("appid", configPay.getWeixin().getAppId());//微信开放平台审核通过的应用APPID
        map.put("mch_id", configPay.getWeixin().getMchId());//微信支付分配的商户号
        //        map.put("device_info", "WEB");//终端设备号(门店号或收银设备ID)，默认请传"WEB"
        map.put("nonce_str", nonce_str);//随机字符串，不长于32位。推荐随机数生成算法
        map.put("body", body);//商品描述交易字段格式根据不同的应用场景按照以下格式：APP——需传入应用市场上的APP名字-实际商品名称，天天爱消除-游戏充值。
        //        map.put("detail", "Ipad mini  16G  白色");//商品名称明细列表
        map.put("out_trade_no", outTradeNo);//商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
        //        map.put("fee_type", "CNY");//符合ISO 4217标准的三位字母代码，默认人民币：CNY，其他值列表详见货币类型
        map.put("total_fee", totalFee.multiply(BigDecimal.valueOf(100)).longValue() + "");//订单总金额，单位为分，详见支付金额
        map.put("spbill_create_ip", ip);//用户端实际ip
        //String time = DateUtils.getBeijingTimeNow(YYYYMMDDHHMMSS);
        //map.put("time_start", time);
        //订单生成时间，格式为yyyyMMddHHmmss，如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
        //map.put("time_expire", String.valueOf(Long.valueOf(time) + 30L * 60L + 1));
        // 订单失效时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010。其他详见时间规则注意：最短失效时间间隔必须大于5分钟
        //        map.put("goods_tag", "WXG");//商品标记，代金券或立减优惠功能的参数，说明详见代金券或立减优惠
        //        map.put("notify_url", WeixinConfig.notifyUrl);
        map.put("notify_url", notifyUrl);
        //接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
        map.put("trade_type", "APP");//支付类型
        //        map.put("limit_pay", "no_credit");//no_credit--指定不能使用信用卡支付

        map.put("sign", Sign.createSign(map, configPay.getWeixin().getAppKey()));//签名，详见签名生成算法
        return map;
    }


    private String getPrepayId(String response) {
        try {
            logger.debug("微信统一下单返回结果: {}", response);
            Document document = DocumentHelper.parseText(response);
            Element root = document.getRootElement();
            Element returnCode = root.element("return_code");
            if ("SUCCESS".equals(returnCode.getText())) {
                Element resultCode = root.element("result_code");
                if ("SUCCESS".equals(resultCode.getText())) {
                    Element prepayId = root.element("prepay_id");
                    // pay params
                    return prepayId.getText();
                }
            }
        } catch (Exception e) {
            logger.error("解析微信统一下单返回结果失败", e);
        }
        logger.error("微信下单失败{}", response);
        return null;
    }

    private static final String WEIXIN_PAY_NOTIFY_END_WITH = "weixin pay notify: end with {}";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String payNotify(String resXml) {

        String xmlBack = "";
        Map<String, String> map = null;

        boolean success = true;
        try {
            map = XmlUtils.xmlToMap(DocumentHelper.parseText(resXml));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("weixin pay notify: {}", JSON.toJSONString(map));
        }
        // 交易结果
        String return_code = map.get("return_code");
        if (!"SUCCESS".equals(return_code)) {
            logger.warn(WEIXIN_PAY_NOTIFY_END_WITH, "返回code不是success");
            success = false;
        }
        // 签名验证
        /*String sign = map.get("sign");
        if (!Sign.signValidate(map, sign, appkey)) {
            logger.warn(WEIXIN_PAY_NOTIFY_END_WITH, "签名错误");
            success = false;
        }*/
        // 应用APPID
        String appid = map.get("appid");//微信开放平台审核通过的应用APPID
        if (!configPay.getWeixin().getAppId().equals(appid)) {
            logger.warn(WEIXIN_PAY_NOTIFY_END_WITH, "appId不匹配");
            success = false;
        }
        //商户号
        String mch_id = map.get("mch_id");//微信支付分配的商户号
        if (!configPay.getWeixin().getMchId().equals(mch_id)) {
            logger.warn(WEIXIN_PAY_NOTIFY_END_WITH, "ca商户号不匹配");
            success = false;
        }
        //交易类型
        String trade_type = map.get("trade_type");
        if (!"APP".equals(trade_type)) {
            logger.warn(WEIXIN_PAY_NOTIFY_END_WITH, "支付方式不匹配");
            success = false;
        }
        // 交易结果
        String result_code = map.get("result_code");//业务结果
        if (!"SUCCESS".equals(result_code)) {
            String err_code = map.get("err_code");//错误代码
            String err_code_des = map.get("err_code_des");//错误代码描述
            logger.warn("weixin pay notify: error_code {}", err_code);
            logger.warn("weixin pay notify: err_code_des {}", err_code_des);
            logger.warn(WEIXIN_PAY_NOTIFY_END_WITH, "支付失败");
            success = false;
        }

        if (!success) {
            return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }

        //商户订单号
        String out_trade_no = map.get("out_trade_no");

        //查询交易记录
        UserTrade trade = balanceService.selectTradeByTradeNo(out_trade_no);
        if (Objects.isNull(trade) || trade.getStatus() == 1) {
            return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }

        //金额入账
        balanceService.update(trade.getUserId(), trade.getType() == 0 ? BalanceType.ADD : BalanceType.WEIXIN_CREATE_PACKET, trade.getMoney(), trade.getId(), "微信充值");
        //交易记录状态更新
        balanceService.completeTrade(trade.getId());

        return "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

    }

    private FsResponse xspayOpenAccount(User user, UserBankXs bank) {
//        UserBankXs bank = userBankXsMapper.selectByPrimaryKey(bankId);
//        if (Objects.isNull(bank)) {
//            return FsResponseGen.failMsg("银行卡不存在");
//        }
//        if (!userId.equals(bank.getUserId())) {
//            return FsResponseGen.failMsg("银行卡错误");
//        }
//
//        User user = userMapper.selectByPrimaryKey(userId);
        if (Objects.nonNull(user.getXspayuserid())) {
            return FsResponseGen.successData(user.getXspayuserid());
        }

        R010TransForm r010TransForm = new R010TransForm();
        r010TransForm.setTranCode("R010");
        r010TransForm.initCommonParams("R010", configPay.getxSpay().getMerId(), null);
        r010TransForm.setSubmitUrl("https://ncount.hnapay.com/api/r010.htm");
        r010TransForm.setMerUserId(String.valueOf(user.getId()));
        r010TransForm.setMobile(bank.getMobile());
        r010TransForm.setUserName(bank.getName());
        r010TransForm.setCertNo(bank.getIdNumber());

        try {
            Map<String, Object> result = XSpayService.getInstance().post(r010TransForm, R010TransForm.verifyArr);
            if (Objects.isNull(result)) {
                return FsResponseGen.failMsg("校验失败");
            }
            if ("0000".equals(result.get("resultCode"))) {
                String xsUserId = result.get("userId").toString();
                user.setXspayuserid(xsUserId);
//                user.setXspaybankid(bank.getId());
                userMapper.updateByPrimaryKeySelective(user);
                return FsResponseGen.successData(xsUserId);
            } else {
                return FsResponseGen.failMsg(result.get("errorMsg").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return FsResponseGen.failMsg("开户异常");
        }
    }

    @Override
    public FsResponse xspayBindCardPre(Long userId, UserBankXs bank) {
        Example example = new Example(UserBankXs.class);
        example.createCriteria().andEqualTo("bankNumber", bank.getBankNumber()).andEqualTo("userId", userId);
        UserBankXs exist = userBankXsMapper.selectOneByExample(example);
        if (Objects.nonNull(exist)) {
            if (Objects.nonNull(exist.getXsbindcardagrno())) {
                if (exist.getStatus() == 1) {
                    exist.setStatus(0);
                    userBankXsMapper.updateByPrimaryKeySelective(exist);
                    return FsResponseGen.fail(YiChatMsgCode.BANK_DELETE_TO_ADD);
                } else {
                    return FsResponseGen.failMsg("银行卡已存在");
                }
            } else {
                bank.setId(exist.getId());
            }
        }
//        if (!userId.equals(bank.getUserId())) {
//            return FsResponseGen.failMsg("银行卡错误");
//        }
//        if (Objects.nonNull(bank.getXsbindcardagrno())) {
//            return FsResponseGen.failMsg("该卡已绑定过");
//        }

        User user = userMapper.selectByPrimaryKey(userId);
        if (!user.getIdNumber().equals(bank.getIdNumber())) {
            return FsResponseGen.failMsg("只能绑定自己名下的银行卡");
        }

        //绑卡前先校验开户
        FsResponse response = xspayOpenAccount(user, bank);
        if (!response.isSuccess()) {
            return response;
        }

        R007TransForm r007TransForm = new R007TransForm();
        r007TransForm.setTranCode("R007");
        r007TransForm.initCommonParams("R007", configPay.getxSpay().getMerId(), null);
        r007TransForm.setSubmitUrl("https://ncount.hnapay.com/api/r007.htm");
        r007TransForm.setCardNo(bank.getBankNumber());
        r007TransForm.setHolderName(bank.getName());
        r007TransForm.setCardAvailableDate("");
        r007TransForm.setCvv2("");
        r007TransForm.setMobileNo(bank.getMobile());
        r007TransForm.setIdentityType("1");
        r007TransForm.setIdentityCode(bank.getIdNumber());
        r007TransForm.setUserId(user.getXspayuserid());
        r007TransForm.setMerUserIp("127.0.0.1");

        try {
            Map<String, Object> result = XSpayService.getInstance().post(r007TransForm, R007TransForm.verifyArr);
            if (Objects.isNull(result)) {
                return FsResponseGen.failMsg("校验失败");
            }
            if ("0000".equals(result.get("resultCode"))) {
                bank.setXsbindcardordercode(result.get("ncountOrderId").toString());
                if (Objects.nonNull(bank.getId())) {
                    userBankXsMapper.updateByPrimaryKeySelective(bank);
                } else {
                    userBankXsMapper.insertSelective(bank);
                }
                return FsResponseGen.successData(result);
            } else {
//                if ("100E0235".equals(result.get("errorCode").toString())) {
//                    if (Objects.nonNull(user.getXspaybankid())) {
//                        UserBankXs bank1 = userBankXsMapper.selectByPrimaryKey(user.getXspaybankid());
//                        return FsResponseGen.failMsg("只能选择\"" + bank1.getName() + "\"名下的银行卡");
//                    }
//                }
                return FsResponseGen.failMsg(result.get("errorMsg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return FsResponseGen.failMsg("绑卡请求异常");
        }
    }

    @Override
    public FsResponse xspayBindCardConfirm(String orderCode, String ncountOrderId, String smsCode) {
        R008TransForm r008TransForm = new R008TransForm();
        r008TransForm.setTranCode("R008");
        r008TransForm.initCommonParams("R008", configPay.getxSpay().getMerId(), orderCode);
        r008TransForm.setSubmitUrl("https://ncount.hnapay.com/api/r008.htm");
        r008TransForm.setNcountOrderId(ncountOrderId);
        r008TransForm.setSmsCode(smsCode);
        r008TransForm.setMerUserIp("127.0.0.1");

        try {
            Map<String, Object> result = XSpayService.getInstance().post(r008TransForm, R008TransForm.verifyArr);
            if (Objects.isNull(result)) {
                return FsResponseGen.failMsg("校验失败");
            }
            if ("0000".equals(result.get("resultCode"))) {
                Example example = new Example(UserBankXs.class);
                example.createCriteria().andEqualTo("xsbindcardordercode", ncountOrderId);
                UserBankXs bank = userBankXsMapper.selectOneByExample(example);
                bank.setXsbankcode(result.get("bankCode").toString());
                bank.setXsbindcardagrno(result.get("bindCardAgrNo").toString());
                bank.setXscardtype(Integer.valueOf(result.get("cardType").toString()));
                userBankXsMapper.updateByPrimaryKeySelective(bank);

                return FsResponseGen.successData(result);
            } else {
                return FsResponseGen.failMsg(result.get("errorMsg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return FsResponseGen.failMsg("绑卡异常");
        }
    }

    @Override
    public FsResponse xspayPre(String orderCode, Long userId, Integer tradeType, BigDecimal money, Integer bankId) {
        if (money.compareTo(BigDecimal.ZERO) <= 0) {
            return FsResponseGen.failMsg("金额必须大于0");
        }
        UserBankXs bank = userBankXsMapper.selectByPrimaryKey(bankId);
        if (Objects.isNull(bank)) {
            return FsResponseGen.failMsg("银行卡不存在");
        }
        if (!userId.equals(bank.getUserId())) {
            return FsResponseGen.failMsg("银行卡错误");
        }
        //生成交易记录
        balanceService.createTradeRecord(userId, orderCode, money, PayType.XSPAY, tradeType);

        T007TransForm t007TransForm = new T007TransForm();
        t007TransForm.setTranCode("T007");
        t007TransForm.initCommonParams("T007", configPay.getxSpay().getMerId(), orderCode);
        t007TransForm.setSubmitUrl("https://ncount.hnapay.com/api/t007.htm");
        t007TransForm.setTranAmount(String.valueOf(money));
        t007TransForm.setReceiveUserId(configPay.getxSpay().getMerId());
        t007TransForm.setDivideDetail("");
        t007TransForm.setDivideFlag("");
        t007TransForm.setGoodsInfo("");
        t007TransForm.setRiskExpand("");
        t007TransForm.setMerUserIp("139.196.17.49");
        t007TransForm.setUserId("");
        t007TransForm.setOrderExpireTime("");
        t007TransForm.setNotifyUrl(configPay.getxSpay().getNotifyUrl());
        t007TransForm.setFrontUrl("");
        t007TransForm.setBindCardAgrNo("");
        t007TransForm.setIdentityCode(bank.getIdNumber());
        t007TransForm.setIdentityType("1");
        t007TransForm.setMobileNo(bank.getMobile());
        t007TransForm.setCvv2("");
        t007TransForm.setCardAvailableDate("");
        t007TransForm.setHolderName(bank.getName());
        t007TransForm.setCardNo(bank.getBankNumber());
        t007TransForm.setPayType("2");
        t007TransForm.setSubMerchantId("2203031717412972172");

        try {
            Map<String, Object> result = XSpayService.getInstance().post(t007TransForm, t007TransForm.getVerifyArr());
            if (Objects.isNull(result)) {
                return FsResponseGen.failMsg("校验失败");
            }
            if ("0000".equals(result.get("resultCode"))) {
                return FsResponseGen.successData(result);
            } else {
                return FsResponseGen.failMsg(result.get("errorMsg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return FsResponseGen.failMsg("下单异常");
        }

    }
//
//    public static void main(String[] args) {
//
//        T007TransForm t007TransForm = new T007TransForm();
//        t007TransForm.setTranCode("T007");
//        t007TransForm.initCommonParams("T007", "300033945241", "30003394521241247");
//        t007TransForm.setSubmitUrl("https://ncount.hnapay.com/api/t007.htm");
//        t007TransForm.setTranAmount(String.valueOf(2000));
//        t007TransForm.setReceiveUserId("300033945241");
//        t007TransForm.setDivideDetail("");
//        t007TransForm.setDivideFlag("");
//        t007TransForm.setGoodsInfo("");
//        t007TransForm.setRiskExpand("");
//        t007TransForm.setMerUserIp("139.196.17.49");
//        t007TransForm.setUserId("");
//        t007TransForm.setOrderExpireTime("");
//        t007TransForm.setNotifyUrl("http://39.105.218.145:8015/api/pay/xspay/xsfjkldnotify");
//        t007TransForm.setFrontUrl("");
//        t007TransForm.setBindCardAgrNo("");
//        t007TransForm.setIdentityCode("340824198803014211");
//        t007TransForm.setIdentityType("1");
//        t007TransForm.setMobileNo("18055171707");
//        t007TransForm.setCvv2("");
//        t007TransForm.setCardAvailableDate("");
//        t007TransForm.setHolderName("黄方意");
//        t007TransForm.setCardNo("6217211302017078410");
//        t007TransForm.setPayType("2");
//        t007TransForm.setSubMerchantId("2203031717412972172");
//
//        try {
//            Map<String, Object> result = XSpayService.getInstance().post(t007TransForm, t007TransForm.getVerifyArr());
//            if (Objects.isNull(result)) {
//                return ;
//            }
//            if ("0000".equals(result.get("resultCode"))) {
//                return ;
//            } else {
//                return  ;
//            }
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//            e.printStackTrace();
//            return  ;
//        }
//
//
//
////        T008TransForm t008TransForm = new T008TransForm();
////        t008TransForm.setTranCode("T008");
////        t008TransForm.initCommonParams("T008", "300033945241", "30003394521241246");
////        t008TransForm.setSubmitUrl("https://ncount.hnapay.com/api/t008.htm");
////        t008TransForm.setNcountOrderId("2022031614068149");
////        t008TransForm.setSmsCode("130800");
////        t008TransForm.setMerUserIp("139.196.17.49");
////        t008TransForm.setBusinessType("");
////        t008TransForm.setFeeType("");
////        t008TransForm.setDivideAcctDtl("");
////        t008TransForm.setFeeAmountUser("");
////        t008TransForm.setPaymentTerminalInfo("|");
////        t008TransForm.setReceiverTerminalInfo("|||");
////        t008TransForm.setDeviceInfo("139.196.17.49||||||");
////
////        try {
////            Map<String, Object> result = XSpayService.getInstance().post(t008TransForm, t008TransForm.getVerifyArr());
////            if (Objects.isNull(result)) {
////                return  ;
////            }
////            if ("9999".equals(result.get("resultCode")) || "0000".equals(result.get("resultCode"))) {
////                return  ;
////            } else {
////                return ;
////            }
////        } catch (Exception e) {
////            logger.error(e.getMessage());
////            e.printStackTrace();
////            return  ;
////        }
//
//    }

//
    public static void main(String[] args) {
        String userIds= "100034047124#" +
                "100034426021#" +
                "100034740579#" +
                "100034923662#";
        String moneys= "8.92#" +
                "8.31#" +
                "8.3#" +
                "26.78#";
        String[] userArr=userIds.split("#");
        String[] moneyArr=moneys.split("#");
        for (int i=0;i<userArr.length;i++){
            String userId=userArr[i];
            String money=moneyArr[i];
            //提现
            T003TransForm t003TransForm = new T003TransForm();
            t003TransForm.setTranCode("T003");
            t003TransForm.initCommonParams("T003","300033945241", null);
            t003TransForm.setSubmitUrl("https://ncount.hnapay.com/api/t003.htm");
            t003TransForm.setPayUserId(userId);
            t003TransForm.setReceiveUserId("300033945241");
            t003TransForm.setTranAmount(String.valueOf(money));
            t003TransForm.setBusinessType("");
            try {
                Map<String, Object> result = XSpayService.getInstance().post(t003TransForm, T003TransForm.verifyArr);
                if (Objects.isNull(result)) {
                    //  return FsResponseGen.failMsg("转账校验失败");
                }
                if ("0000".equals(result.get("resultCode"))) {
                    //   return FsResponseGen.successData(result);
                } else {
                    //  return FsResponseGen.failMsg(result.get("errorMsg").toString());
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


//        T002TransForm t002TransForm = new T002TransForm();
//        t002TransForm.setTranCode("T002");
//        t002TransForm.initCommonParams("T002", "300033945241", null);
//        t002TransForm.setSubmitUrl("https://ncount.hnapay.com/api/t002.htm");
//        t002TransForm.setTranAmount(String.valueOf(10000));
//        t002TransForm.setUserId(String.valueOf("100035577509"));
//
//        t002TransForm.setBindCardAgrNo("202204150003765624");
//        //deng 202203050003592536  100034053247
//        //liang 202203260003697765 100035023561
//        //li 202203170003653022  100034635662
//        //xu 202204100003750258 100035452158
//        //xucheng 202204140003761826 100035548237
//        //liuyong 202204150003765624 100035577509
//        t002TransForm.setNotifyUrl("http://39.105.218.145:8015/api/pay/xspay/xstxnotify2");
//        t002TransForm.setServiceAmount("0.00");
//        t002TransForm.setBusinessType("08");
//        t002TransForm.setUserName("");
//        t002TransForm.setCardNo("");
//        t002TransForm.setPaymentTerminalInfo("|");
//        t002TransForm.setDeviceInfo("139.196.17.49||||||");
//
//        try {
//            Map<String, Object> result = XSpayService.getInstance().post(t002TransForm, T002TransForm.verifyArr);
//            if (Objects.isNull(result)) {
//              //  return FsResponseGen.failMsg("提现校验失败");
//            }
//            if ("9999".equals(result.get("resultCode")) || "0000".equals(result.get("resultCode"))) {
//             //   return FsResponseGen.successData(result);
//            } else {
//               // return FsResponseGen.failMsg(result.get("errorMsg").toString());
//            }
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//            e.printStackTrace();
//          //  return FsResponseGen.failMsg("提现异常");
//       }
    }
    @Override
    public FsResponse xspayConfirm(String orderCode, String ncountOrderId, String smsCode) {
        T008TransForm t008TransForm = new T008TransForm();
        t008TransForm.setTranCode("T008");
        t008TransForm.initCommonParams("T008", configPay.getxSpay().getMerId(), orderCode);
        t008TransForm.setSubmitUrl("https://ncount.hnapay.com/api/t008.htm");
        t008TransForm.setNcountOrderId(ncountOrderId);
        t008TransForm.setSmsCode(smsCode);
        t008TransForm.setMerUserIp("139.196.17.49");
        t008TransForm.setBusinessType("");
        t008TransForm.setFeeType("");
        t008TransForm.setDivideAcctDtl("");
        t008TransForm.setFeeAmountUser("");
        t008TransForm.setPaymentTerminalInfo("|");
        t008TransForm.setReceiverTerminalInfo("|||");
        t008TransForm.setDeviceInfo("139.196.17.49||||||");

        try {
            Map<String, Object> result = XSpayService.getInstance().post(t008TransForm, t008TransForm.getVerifyArr());
            if (Objects.isNull(result)) {
                return FsResponseGen.failMsg("校验失败");
            }
            if ("9999".equals(result.get("resultCode")) || "0000".equals(result.get("resultCode"))) {
                return FsResponseGen.successData(result);
            } else {
                return FsResponseGen.failMsg(result.get("errorMsg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return FsResponseGen.failMsg("支付异常");
        }
    }

    @Override
    public FsResponse xspayWithDraw(Long userId, String bankNumber, BigDecimal money) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (Objects.isNull(user.getXspayuserid())) {
            return FsResponseGen.failMsg("未开户，请使用最新版app进行提现");
        }
        Example example = new Example(UserBankXs.class);
        example.createCriteria().andEqualTo("userId", userId).andEqualTo("bankNumber", bankNumber).andEqualTo("status", 0);
        UserBankXs bank = userBankXsMapper.selectOneByExample(example);
        if (Objects.isNull(bank)) {
            return FsResponseGen.failMsg("未找到银行卡");
        }
        if (Objects.isNull(bank.getXsbindcardagrno())) {
            return FsResponseGen.failMsg("未绑卡");
        }
        if (money.compareTo(BigDecimal.ZERO) <= 0) {
            return FsResponseGen.failMsg("提现金额小于0");
        }

        //转账到私人账户
        FsResponse response = xspayTrans(user, money);
        if (!response.isSuccess()) {
            return response;
        }

        T002TransForm t002TransForm = new T002TransForm();
        t002TransForm.setTranCode("T002");
        t002TransForm.initCommonParams("T002", configPay.getxSpay().getMerId(), null);
        t002TransForm.setSubmitUrl("https://ncount.hnapay.com/api/t002.htm");
        t002TransForm.setTranAmount(String.valueOf(money));
        t002TransForm.setUserId(String.valueOf(user.getXspayuserid()));
        t002TransForm.setBindCardAgrNo(bank.getXsbindcardagrno());
        t002TransForm.setNotifyUrl(configPay.getxSpay().getWithdrawNotifyUrl());
        t002TransForm.setServiceAmount("0.00");
        t002TransForm.setBusinessType("08");
        t002TransForm.setUserName("");
        t002TransForm.setCardNo("");
        t002TransForm.setPaymentTerminalInfo("|");
        t002TransForm.setDeviceInfo("139.196.17.49||||||");

        try {
            Map<String, Object> result = XSpayService.getInstance().post(t002TransForm, T002TransForm.verifyArr);
            if (Objects.isNull(result)) {
                return FsResponseGen.failMsg("提现校验失败");
            }
            if ("9999".equals(result.get("resultCode")) || "0000".equals(result.get("resultCode"))) {
                return FsResponseGen.successData(result);
            } else {
                return FsResponseGen.failMsg(result.get("errorMsg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return FsResponseGen.failMsg("提现异常");
        }
    }

    @Override
    public FsResponse xspayGetAccount() {
        Q001TransForm q001TransForm = new Q001TransForm();
        q001TransForm.setTranCode("Q001");
        q001TransForm.initCommonParams("Q001", configPay.getxSpay().getMerId(), null);
        q001TransForm.setSubmitUrl("https://ncount.hnapay.com/api/q001.htm");
        q001TransForm.setUserId(configPay.getxSpay().getMerId());
        try {
            Map<String, Object> result = XSpayService.getInstance().post(q001TransForm, Q001TransForm.verifyArr);
            if (Objects.isNull(result)) {
                return FsResponseGen.failMsg("查询失败");
            }
            if ("0000".equals(result.get("resultCode"))) {
                return FsResponseGen.successData(result);
            } else {
                return FsResponseGen.failMsg(result.get("errorMsg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return FsResponseGen.failMsg("查询异常");
        }
    }

    private FsResponse xspayTrans(User user, BigDecimal money) {
        T003TransForm t003TransForm = new T003TransForm();
        t003TransForm.setTranCode("T003");
        t003TransForm.initCommonParams("T003", configPay.getxSpay().getMerId(), null);
        t003TransForm.setSubmitUrl("https://ncount.hnapay.com/api/t003.htm");
        t003TransForm.setPayUserId(configPay.getxSpay().getMerId());
        t003TransForm.setReceiveUserId(user.getXspayuserid());
        t003TransForm.setTranAmount(String.valueOf(money));
        t003TransForm.setBusinessType("");
        try {
            Map<String, Object> result = XSpayService.getInstance().post(t003TransForm, T003TransForm.verifyArr);
            if (Objects.isNull(result)) {
                return FsResponseGen.failMsg("转账校验失败");
            }
            if ("0000".equals(result.get("resultCode"))) {
                return FsResponseGen.successData(result);
            } else {
                return FsResponseGen.failMsg(result.get("errorMsg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return FsResponseGen.failMsg("转账异常");
        }
    }

//    private List<UserBankXs> getXsBindUserBanks(Long userId) {
//        Example example = new Example(UserBankXs.class);
//        example.createCriteria().andEqualTo("userId", userId).andIsNotNull("xsbindcardagrno").andEqualTo("status", 0);
//        return userBankXsMapper.selectByExample(example);
//    }

    @Override
    public void xspayNotify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        logger.debug("新生支付回调：。。。。。。。。");
//        String encoding = req.getParameter(SDKConstants.param_encoding);
//        // 获取银联通知服务器发送的后台通知参数
        Map reqParam = getAllRequestParam(req);
        logger.debug(JSONObject.toJSONString(reqParam));
//
        //重要！验证签名前不要修改reqParam中的键值对的内容，否则会验签不过
        String[] verifyFields = new String[]{"version", "tranCode", "merOrderId", "merId", "charset", "signType", "resultCode", "errorCode", "ncountOrderId", "tranAmount", "checkDate", "submitTime", "tranFinishTime", "bankCode", "cardType", "shortCardNo", "bindCardAgrNo"};

        boolean verifyResult = false;
        try {
            verifyResult = XSpayService.isVerifyResult(verifyFields, reqParam);
        } catch (XSpayException e) {
            e.printStackTrace();
        }

        if (verifyResult) {
            logger.debug("验证签名结果[成功].");
            //【注：为了安全验签成功才应该写商户的成功处理逻辑】交易成功，更新商户订单状态

            String resultCode = reqParam.get("resultCode").toString(); //获取后台通知的数据，其他字段也可用类似方式获取
            if (!"0000".equals(resultCode)) {
                logger.debug("支付失败");
                return;
            }

            String orderId = reqParam.get("merOrderId").toString(); //获取后台通知的数据，其他字段也可用类似方式获取
            //查询交易记录
            UserTrade trade = balanceService.selectTradeByTradeNo(orderId);
            if (Objects.isNull(trade) || trade.getStatus() == 1) {
                logger.debug("trade错误:{}", orderId);
                return;
            }

            BalanceType balanceType;
            String memo;
            if (trade.getType() == 0) {
                memo = "新生支付充值到余额";
                balanceType = BalanceType.ADD;

                //金额入账
                balanceService.update(trade.getUserId(), balanceType, trade.getMoney(), trade.getId(), memo);
                pushService.sendServiceSingle(2,null,DateUtils.formatDate(trade.getCtime()),trade.getId(),trade.getUserId(), "充值成功",trade.getMoney(), "成功充值【" + trade.getMoney()+ "】元", false);

            } else if (trade.getType() == 1) {
                balanceType = BalanceType.ALIPAY_CREATE_PACKET;
                memo = "新生支付充值创建红包";

                //金额入账
                balanceService.update(trade.getUserId(), balanceType, trade.getMoney(), trade.getId(), memo);
                pushService.sendServiceSingle(2,null,DateUtils.formatDate(trade.getCtime()),trade.getId(),trade.getUserId(), "充值成功",trade.getMoney(), "成功充值【" + trade.getMoney()+ "】元", false);


            } else if (trade.getType() == 2) {
//                ShoppingOrder order = new ShoppingOrder();
//                order.setOrderStatus(1);
//                Example example = new Example(ShoppingOrder.class);
//                example.createCriteria().andEqualTo("orderCode", trade.getTradeNo());
//                orderMapper.updateByExampleSelective(order, example);
            }

            //交易记录状态更新
            balanceService.completeTrade(trade.getId());
        }
        logger.debug("新生支付接收后台通知结束");
    }


    /**
     * 获取请求参数中所有的信息
     *
     * @param request
     * @return
     */
    private static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
                //System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }

    @Override
    public String alipayPre(Long userId, Integer tradeType, BigDecimal money) {


        logger.debug("支付宝预下单。。。。");

        //暂时订单号使用
        String out_trade_no = DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS") + userId;
        //生成交易记录
        balanceService.createTradeRecord(userId, out_trade_no, money, PayType.ALIPAY, tradeType);

        // 获取配置文件中支付宝相关信息
        String aliPayGateway = "https://openapi.alipay.com/gateway.do";
        String signType = "RSA2";
        String alipayFormat = "json";
        String alipayCharset = "utf-8";

        AlipayClient alipayClient = new DefaultAlipayClient(aliPayGateway, configPay.getAlipay().getAppId(), configPay.getAlipay().getPrivateKey(), alipayFormat, alipayCharset, configPay.getAlipay().getAppPublicKey(), signType);
        AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        //在body里存储跳转信息
        String redirect = configPay.getAlipay().getRedirectUrl();
        model.setBody("支付宝充值" + (StringUtils.isNotBlank(redirect) ? ("zf" + redirect) : ""));
        model.setSubject("支付宝充值");
        // 唯一订单号 根据项目中实际需要获取相应的
        model.setOutTradeNo(out_trade_no);
        // 支付超时时间（根据项目需要填写）
        model.setTimeoutExpress("10m");
        // 支付金额（项目中实际订单的需要支付的金额，金额的获取与操作请放在服务端完成，相对安全）
        model.setTotalAmount(NumberUtils.scale2HalfUp(money).toString());
        model.setProductCode("QUICK_MSECURITY_PAY");
        alipayRequest.setBizModel(model);
        // 支付成功后支付宝异步通知的接收地址url
        //alipayRequest.setNotifyUrl("http://47.56.123.244:8015/api/pay/alipay/notify");
        alipayRequest.setNotifyUrl(configPay.getAlipay().getNotifyUrl());

        AlipayTradeAppPayResponse alipayResponse = null;
        try {
            logger.debug("开始请求执行预支付接口。。。");
            logger.debug(JSON.toJSONString(alipayRequest));
            alipayResponse = alipayClient.sdkExecute(alipayRequest);
            logger.debug("请求结果:" + JSON.toJSONString(alipayResponse));
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        // 返回支付相关信息(此处可以直接将getBody中的内容直接返回，无需再做一些其他操作)
        return alipayResponse.getBody();
    }


    @Override
    public FsResponse transferAlipayAccount(String appOrderNO, String account, BigDecimal money) {


        //商户订单号

        //初始化客户端
        DefaultAlipayClient alipayClien = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", configPay.getAlipay().getAppId(), configPay.getAlipay().getPrivateKey(), "JSON", "UTF-8", configPay.getAlipay().getPublicKey(), "RSA2");

        //实例化提现请求
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();

        //参数对象
        AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
        model.setOutBizNo(appOrderNO);
        model.setAmount(money.toString());
        model.setPayeeType("ALIPAY_LOGONID");
        //收款方账号
        model.setPayeeAccount(account);
        model.setRemark("APP提现");
        //绑定参数model
        request.setBizModel(model);
        try {
            //执行请求
            AlipayFundTransToaccountTransferResponse response = alipayClien.execute(request);


            if (response.isSuccess()) {
                //转账成功
                return FsResponseGen.success();
            } else {
                return FsResponseGen.failMsg(response.getCode() + "," + response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return FsResponseGen.failMsg("系统异常");
    }



}
